// pages/picdisplay/picdisplay.js
const app = getApp();
let util = require("../../utils/util");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentPic: "",
    result: [],
    isCollect: false,
    introduction: "",
    disabled: false,
    collectTimes: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let pic_src = options.pic_src;

    //console.log(pic_src);
    this.setData({
      currentPic: pic_src,
    });

    this.getImageBase64(pic_src);

    //隐藏右上角的分享按钮
    wx.hideShareMenu({});
  },

  //将图片base64化并发送识别请求
  getImageBase64(imagePath) {
    wx.getFileSystemManager().readFile({
      filePath: imagePath,
      encoding: "base64",
      success: (res) => {
        //let img_src = encodeURIComponent(imgBase64);
        this.handlePostHttp(res.data, app.globalData.token);
      },
    });
  },

  //文字识别
  handlePostHttp(pic_src, token) {
    wx.showLoading({
      title: "识别中...",
    });
    wx.request({
      url: `https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=${token}`,
      data: {
        image: pic_src,
      },
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded",
      },
      success: (res) => {
        //console.log(res.data);
        this.setData({
          result: res.data.words_result,
          introduction: res.data.words_result[0].words,
        });
        wx.hideLoading({}); //识别结束
      },
    });
  },
  //点击查看大图
  toViewLarger() {
    wx.previewImage({
      urls: [this.data.currentPic],
    });
  },

  //复制识别结果
  setClipboard() {
    // console.log("开始复制");
    let data = "";
    this.data.result.forEach((element) => {
      data += element.words;
    });
    console.log(data);
    wx.setClipboardData({
      data: data,
      success: () => {
        wx.showToast({
          title: "复制成功",
          icon: "success",
          duration: 1000,
        });
      },
    });
  },
  //添加到识别记录里
  collectToRecord(mes) {
    console.log(mes);
    const that = this;
    that.setData({
      isCollect: true,
      disabled: true,
    });

    if (that.data.isCollect) {
      that.setData({
        collectTimes: mes.currentTarget.dataset.index + 1,
      });

      let resultObj = {
        time: util.formatTime(new Date()),
        title: that.data.introduction,
        imgsrc: that.data.currentPic,
      };

      wx.setStorageSync("res", resultObj);

      if (that.data.disabled) {
        wx.showToast({
          title: "已添加",
          icon: "info",
          duration: 1000,
        });
      }
    }
  },

  //转发分享
  onShareAppMessage: function (res) {
    console.log(res);
    let { currentpic } = res.target.dataset;
    let shareObj = {
      title: "识别结果",
      path: "/pages/picdisplay/picdisplay?pic_src=" + currentpic,
    };
    return shareObj;
  },

  //监听下拉刷新
  onPullDownRefresh: function (options) {
    this.getImageBase64(this.data.currentPic);
  },
});
